/*Scala code license:

 Copyright 2009/10 Osman Pub

 Licensed under the Apache License, Version 2.0 (the "License") you may not use
 this file except in compliance with the License.

 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software distributed
 under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 CONDITIONS OF ANY KIND, either express or implied. See the License for the
 specific language governing permissions and limitations under the License.

 */
/**
 Orginal java code credits:
 * @author Kevin J. Duling
 */
package demos

import common._
import java.awt.event._
import javax.media.opengl._
import javax.media.opengl.glu.GLU
import javax.swing._

object Lesson08 {
  def main(args: Array[String]) {
    val glDisplay = GLDisplay("Lesson 08: Blending")
    glDisplay addGLEventListener new Renderer
    glDisplay addKeyListener new KeyAdapter {
      override def keyPressed(e: KeyEvent) =
        response = e getKeyCode match {
          case KeyEvent.VK_PAGE_UP => Action zoomIn
          case KeyEvent.VK_PAGE_DOWN => Action zoomOut
          case KeyEvent.VK_UP => Action incX
          case KeyEvent.VK_DOWN => Action decX
          case KeyEvent.VK_RIGHT => Action incY
          case KeyEvent.VK_LEFT => Action decY
          case _ => Action none
        }

      override def keyReleased(e: KeyEvent) =
        e getKeyCode match {
          case KeyEvent.VK_ESCAPE => glDisplay stop
          case KeyEvent.VK_B => response = Action blending
          case KeyEvent.VK_F => response = Action filter
          case KeyEvent.VK_L => response = Action lighting
          case _ => response = Action none
        }
    }
    glDisplay start
  }

  object Action extends Enumeration { val blending, incX, decX, incY, decY,
                               filter, lighting, none, zoomIn, zoomOut = Value }
  private var response = Action none

  private class Renderer extends GLEventListener {
    /** Called by the drawable to initiate OpenGL rendering by the client.
     * After all GLEventListeners have been notified of a display event, the
     * drawable will swap its buffers if necessary.
     * @param gLDrawable The GLAutoDrawable object.
     */
    private val glu = new GLU
    private val textures = new Array[Int](3)

    private var filter = 0
    private var blending, lighting = true
    private var xSpeed, ySpeed, xrot, yrot, zrot: Float = 0
    private var z = -5.0f			// Depth Into The Screen

    def display(glDrawable: GLAutoDrawable) {
      def update {
        response match {
          case Action.blending => blending = !blending
          case Action.filter => filter = (filter + 1) % textures.length
          case Action.lighting => lighting = !lighting
          case Action.incX => xSpeed += 0.01f
          case Action.decX => xSpeed -= 0.01f
          case Action.incY => ySpeed += 0.01f
          case Action.decY => ySpeed -= 0.01f
          case Action.zoomIn => z += 0.02f
          case Action.zoomOut => z -= 0.02f
          case _ =>
        }
        response = Action none
      }

      val gl = glDrawable.getGL
      gl glClear GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT
      gl glLoadIdentity; gl glTranslatef(0, 0, z)
      gl glRotatef(xrot, 1, 0, 0); gl glRotatef(yrot, 0, 1, 0)
      gl glBindTexture(GL GL_TEXTURE_2D, textures(filter))

      if(lighting) gl glEnable GL.GL_LIGHTING
      else gl glDisable GL.GL_LIGHTING

      if(blending) { gl glEnable GL.GL_BLEND; gl glDisable GL.GL_DEPTH_TEST	}
      else { gl glDisable GL.GL_BLEND; gl glEnable GL.GL_DEPTH_TEST }

      gl glBegin GL.GL_QUADS

      // Front Face
      gl glNormal3f(0, 0, 1)
      gl glTexCoord2f(0, 0); gl glVertex3f(-1, -1, 1)
      gl glTexCoord2f(1, 0); gl glVertex3f(1, -1, 1)
      gl glTexCoord2f(1, 1); gl glVertex3f(1, 1, 1)
      gl glTexCoord2f(0, 1); gl glVertex3f(-1, 1, 1)

      // Back Face
      gl glNormal3f(0, 0, -1)
      gl glTexCoord2f(1, 0); gl glVertex3f(-1, -1, -1)
      gl glTexCoord2f(1, 1); gl glVertex3f(-1, 1, -1)
      gl glTexCoord2f(0, 1); gl glVertex3f(1, 1, -1)
      gl glTexCoord2f(0, 0); gl glVertex3f(1, -1, -1)

      // Top Face
      gl glNormal3f(0, 1, 0)
      gl glTexCoord2f(0, 1); gl glVertex3f(-1, 1, -1)
      gl glTexCoord2f(0, 0); gl glVertex3f(-1, 1, 1)
      gl glTexCoord2f(1, 0); gl glVertex3f(1, 1, 1)
      gl glTexCoord2f(1, 1); gl glVertex3f(1, 1, -1)

      // Bottom Face
      gl glNormal3f(0, -1, 0)
      gl glTexCoord2f(1, 1); gl glVertex3f(-1, -1, -1)
      gl glTexCoord2f(0, 1); gl glVertex3f(1, -1, -1)
      gl glTexCoord2f(0, 0); gl glVertex3f(1, -1, 1)
      gl glTexCoord2f(1, 0); gl glVertex3f(-1, -1, 1)

      // Right face
      gl glNormal3f(1, 0, 0)
      gl glTexCoord2f(1, 0); gl glVertex3f(1, -1, -1)
      gl glTexCoord2f(1, 1); gl glVertex3f(1, 1, -1)
      gl glTexCoord2f(0, 1); gl glVertex3f(1, 1, 1)
      gl glTexCoord2f(0, 0); gl glVertex3f(1, -1, 1)

      // Left Face
      gl glNormal3f(-1, 0, 0)
      gl glTexCoord2f(0, 0); gl glVertex3f(-1, -1, -1)
      gl glTexCoord2f(1, 0); gl glVertex3f(-1, -1, 1)
      gl glTexCoord2f(1, 1); gl glVertex3f(-1, 1, 1)
      gl glTexCoord2f(0, 1); gl glVertex3f(-1, 1, -1)
      gl glEnd

      xrot += xSpeed; yrot += ySpeed
      if(response != Action.none) update
    }

    /** Called when the display mode has been changed.  <B>!!
     * CURRENTLY UNIMPLEMENTED IN JOGL !!</B>
     * @param gLDrawable The GLAutoDrawable object.
     * @param modeChanged Indicates if the video mode has changed.
     * @param deviceChanged Indicates if the video device has changed.
     */
    def displayChanged(glDrawable: GLAutoDrawable, modeChanged: Boolean,
                       deviceChanged: Boolean) {}

    /** Called by the drawable immediately after the OpenGL context is
     * initialized for the first time. Can be used to perform one-time OpenGL
     * initialization such as setup of lights and display lists.
     * @param gLDrawable The GLAutoDrawable object.
     */
    def init(glDrawable: GLAutoDrawable) {
      val gl = glDrawable.getGL

      def loadGLTextures {
        val textImg = TextureReader readTexture "demos/data/images/glass.png"

        //Create Nearest Filtered Texture
        gl glGenTextures(3, textures, 0)

        gl glBindTexture(GL GL_TEXTURE_2D, textures(0))
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MAG_FILTER,
                           GL GL_NEAREST)
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MIN_FILTER,
                           GL GL_NEAREST)
        gl glTexImage2D(GL GL_TEXTURE_2D, 0, GL GL_RGB, textImg width,
          textImg height, 0,  GL GL_RGB, GL GL_UNSIGNED_BYTE, textImg pixels)

        //Create Linear Filtered Texture
        gl glBindTexture(GL GL_TEXTURE_2D, textures(1))
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MAG_FILTER,
                           GL GL_LINEAR)
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MIN_FILTER,
                           GL GL_LINEAR)
        gl glTexImage2D(GL GL_TEXTURE_2D, 0, GL GL_RGB, textImg width,
          textImg height, 0,  GL GL_RGB, GL GL_UNSIGNED_BYTE, textImg pixels)

        //Create MipMapped Texture (Only with GL4Java 2.1.2.1 and later!)
        gl glBindTexture(GL GL_TEXTURE_2D, textures(2))
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MAG_FILTER,
                           GL GL_LINEAR)
        gl glTexParameteri(GL GL_TEXTURE_2D, GL GL_TEXTURE_MIN_FILTER,
                           GL GL_LINEAR_MIPMAP_NEAREST)
        glu gluBuild2DMipmaps(GL GL_TEXTURE_2D, GL GL_RGB8, textImg width,
          textImg height, GL GL_RGB, GL GL_UNSIGNED_BYTE, textImg pixels)
      }

      // init
      loadGLTextures

      gl glShadeModel GL.GL_SMOOTH               // Enable Smooth Shading
      gl glClearColor(0, 0, 0, 0)     // Black Background
      gl glClearDepth 1                       // Depth Buffer Setup
      gl glEnable GL.GL_DEPTH_TEST 							// Enables Depth Testing
      gl glDepthFunc GL.GL_LEQUAL 						// The Type Of Depth Testing To Do
      gl glHint(GL GL_PERSPECTIVE_CORRECTION_HINT, GL GL_NICEST)
      gl glEnable GL.GL_TEXTURE_2D

      // Set up lighting
      val lightAmbient = Array(0.5f, 0.5f, 0.5f, 1.0f)
      val lightDiffuse = Array(1.0f, 1.0f, 1.0f, 1.0f)
      val lightPosition = Array(0.0f, 0.0f, 2.0f, 1.0f)

      gl glLightfv(GL GL_LIGHT1, GL GL_AMBIENT, lightAmbient, 0)
      gl glLightfv(GL GL_LIGHT1, GL GL_DIFFUSE, lightDiffuse, 0)
      gl glLightfv(GL GL_LIGHT1, GL GL_POSITION, lightPosition, 0)
      gl glEnable(GL GL_LIGHT1)

      gl glColor4f(1, 1, 1, 0.5f)					// Full Brightness.  50% Alpha (new)
      gl glBlendFunc(GL GL_SRC_ALPHA, GL GL_ONE)			
    }

    /** Called by the drawable during the first repaint after the component has
     * been resized. The client can update the viewport and view volume of the
     * window appropriately, for example by a call to
     * GL.glViewport(int, int, int, int) note that for convenience the component
     * has already called GL.glViewport(int, int, int, int)(x, y, width, height)
     * when this method is called, so the client may not have to do anything in
     * this method.
     * @param gLDrawable The GLAutoDrawable object.
     * @param x The X Coordinate of the viewport rectangle.
     * @param y The Y coordinate of the viewport rectanble.
     * @param width The new width of the window.
     * @param height The new height of the window.
     */
    def reshape(glDrawable: GLAutoDrawable, x: Int, y: Int, width: Int,
                height: Int) {
      require(height != 0)
      val gl = glDrawable getGL;

      gl glMatrixMode GL.GL_PROJECTION; gl glLoadIdentity;
      glu gluPerspective(45, width.asInstanceOf[Float] /
                         height.asInstanceOf[Float], 1, 20)
      gl glMatrixMode GL.GL_MODELVIEW; gl glLoadIdentity
    }
  }
}